package com.ctyun.xstore.vod.internal;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

public final class AESCipherUtils {

	private static final String ALGORITHM = "AES";

	private static final int KEY_LEN = 128;

	private AESCipherUtils() {
		super();
	}

	public static byte[] encrypt(byte[] data, String password) {
		return doCipher(data, password, Cipher.ENCRYPT_MODE);
	}

	public static byte[] decrypt(byte[] data, String password) {
		return doCipher(data, password, Cipher.DECRYPT_MODE);
	}

	private static byte[] doCipher(byte[] data, String password, int mode) {
		try {
			byte[] key = getKey(password);

			SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			cipher.init(mode, keySpec);
			return cipher.doFinal(data);
		} catch (Throwable t) {
			throw new RuntimeException(t);
		}
	}

	private static byte[] getKey(String password) throws NoSuchAlgorithmException {
		SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
		random.setSeed(password.getBytes());

		KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
		keyGen.init(KEY_LEN, random);
		return keyGen.generateKey().getEncoded();
	}
}
